package com.igeekhome.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.igeekhome.dto.NetworkDto;
import com.igeekhome.dto.SectionNetworkDto;
import com.igeekhome.mapper.DNetworkMapper;
import com.igeekhome.mapper.NetworkDtoMapper;
import com.igeekhome.pojo.DNetwork;
import com.igeekhome.pojo.DNetworkExample;
import com.igeekhome.service.INetworkService;
import com.igeekhome.util.CommonUtil;
import com.igeekhome.util.DtreeLayUINode;
import com.igeekhome.util.ResultBean;
import com.igeekhome.util.TableResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Romeo
 */
@Service("networkService")
public class NetworkServiceImpl implements INetworkService {

    @Autowired
    private DNetworkMapper dNetworkMapper;
    
    @Autowired
    private NetworkDtoMapper networkDtoMapper;
    @Override
    public DtreeLayUINode selectByIdToTree(Integer nid) {
        // 得到当前所在网点
        DNetwork myNetwork = dNetworkMapper.selectByPrimaryKey(nid);
        // 将当前网点的类型转换为DtreeLayUINode以便页面显示
        DtreeLayUINode dtree = NetworkToDtree(myNetwork);
        // 得到所有网点信息
        DNetworkExample example = new DNetworkExample();
        example.createCriteria().andStatusEqualTo(1);
        List<DNetwork> network = dNetworkMapper.selectByExample(example);
        // 将所有网点与当前网点进行比对，得到对应的子网点
        List<DtreeLayUINode> firstChilds = getChildren(network, nid);
        // 将对应的子网点塞入children中
        dtree.setChildren(firstChilds);
        // 向下遍历继续寻找，由于最高只有三层（1.当前网点，2.firstChilds,3.children)如果没有三层则会塞null
        for (DtreeLayUINode fc : firstChilds) {

            List<DtreeLayUINode> children = getChildren(network, Integer.parseInt(fc.getId()));
            fc.setChildren(children);
        }
        // 最后返回网点的信息
        return dtree;
    }

    @Override
    public List<DNetwork> selectByCondition(DNetwork dNetwork) {
        DNetworkExample example = new DNetworkExample();
        DNetworkExample.Criteria criteria = example.createCriteria();
        String addressId = dNetwork.getAddressId();
        Integer networkId = dNetwork.getNetworkId();
        String networkName = dNetwork.getNetworkName();

        if (!CommonUtil.isEmpty(addressId) ) {
            criteria.andAddressIdLike(addressId);
        }
        if (networkId !=null) {
            criteria.andNetworkIdEqualTo(networkId);
        }
        if (CommonUtil.isEmpty(networkName)) {
            criteria.andNetworkNameLike(networkName);
        }

        List<DNetwork> dNetworks = dNetworkMapper.selectByExample(example);
        return dNetworks;
    }

    @Override
    public List<SectionNetworkDto> selectNetworkInIds(String strId) {
        List<SectionNetworkDto> sectionNetworkDtos = dNetworkMapper.selectNetworkInIds(strId);
        return sectionNetworkDtos;
    }

    @Override
    public TableResultBean selectByIdToTable(Integer nid, Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        String nids = networkDtoMapper.selectNetworkChild(nid);
        List<NetworkDto> networkDtos = networkDtoMapper.selectByIds(nids);
        for(NetworkDto networkDto : networkDtos ){
            String[] address = CommonUtil.addressToList(networkDto.getAddress());
            if(address.length == 4){
                networkDto.setProvince(address[0]);
                networkDto.setCity(address[1]);
                networkDto.setArea(address[2]);
                networkDto.setAddress(address[3]);
            }

        }
        PageInfo<NetworkDto> pageInfo = new PageInfo<>(networkDtos);
        if(networkDtos != null){
            return TableResultBean.ok(pageInfo.getTotal(),networkDtos);
        }
        return TableResultBean.fail("暂未信息");
    }

    @Override
    public List<DNetwork> selectAll() {
        DNetworkExample example = new DNetworkExample();
        example.createCriteria().andStatusEqualTo(1);
        return dNetworkMapper.selectByExample(example);
    }

    @Override
    public ResultBean add(DNetwork dNetwork, String province, String city, String area, String address) {
        String address_id = CommonUtil.toSplicing(province, city, area, address);
        dNetwork.setAddressId(address_id).setStatus(1);
        int insert = dNetworkMapper.insertSelective(dNetwork);
        if(insert > 0){
            return  ResultBean.success();
        }
        return ResultBean.fail("新增失败");
    }

    @Override
    public ResultBean edit(DNetwork dNetwork, String province, String city, String area, String address) {
        String address_id = CommonUtil.toSplicing(province, city, area, address);
        dNetwork.setAddressId(address_id);
        int update = dNetworkMapper.updateByPrimaryKeySelective(dNetwork);
        if(update > 0){
            return ResultBean.success();
        }
        return ResultBean.fail("更新失败");
    }

    @Override
    public ResultBean logicDelete(Integer nid) {
        String nids = networkDtoMapper.selectNetworkChild(nid);
        Integer logicDelete = networkDtoMapper.logicDelete(nids);
        if(logicDelete > 0){
            return ResultBean.success();
        }
        return ResultBean.fail("删除失败");
    }





    /**
     * 获取网点id为parentId的所有子网点
     * @param network 需要查询的所有网点集合
     * @param parentId 网点id需要得到的网点
     * @return 子网点的前台页面所需的dtree集合
     */
    private List<DtreeLayUINode> getChildren(List<DNetwork> network, Integer parentId) {
        List<DtreeLayUINode> childs = new ArrayList<>();
        for (DNetwork n : network) {
            /**
             * 7. 【强制】所有整型包装类对象之间值的比较， 全部使用equals方法比较。 说明：对于Integer var = ?
             * 在-128至127范围内的赋值，
             * Integer 对象是在 IntegerCache.cache 产 生，
             * 会复用已有对象， 这个区间内的 Integer
             * 值可以直接使用==进行判断， 但是这个区间之外的所有数 据，
             * 都会在堆上产生，并不会复用已有对象， 这是一个大坑，推荐使用 equals方法进行判断
             */
            if (parentId.equals(n.getParentNetworkId())) {
                DtreeLayUINode net = new DtreeLayUINode(n.getNetworkId().toString(), n.getNetworkName(),
                        n.getParentNetworkId().toString(),"" , new ArrayList<>());
                childs.add(net);
            }

        }

        return childs;

    }

    /**
     * 类型转换将DNetwork转换成前台需要的Dtree类型
     * @param n DNetwork类型
     * @return DtreeLayUINode类型
     */
    private DtreeLayUINode NetworkToDtree(DNetwork n) {
        if (n.getParentNetworkId() == null) {
            return new DtreeLayUINode(n.getNetworkId().toString(), n.getNetworkName(), "0","", null);
        }
        return new DtreeLayUINode(n.getNetworkId().toString(), n.getNetworkName(),
                n.getParentNetworkId().toString(),"", null);

    }



}
